#!/usr/bin/env bash


help(){
    cat<<__EOF__
Usage: m network [OPTIONS]

Description: Manage network interfaces and locations on macOS.

Options:
  --help                                            Show this help message and exit
  --list                                            List all network interfaces and their IP addresses
  --location <info|list|create|delete|switch> NAME  Manage network locations (info & list don't require NAME)
__EOF__

}

list_netservices(){
    networksetup -listallhardwareports | while IFS= read -r line; do
        # if it is a device we will print the ip in the next line
        if echo ${line} | grep -i "Device" &>/dev/null; then
            printf "${line}\nIP:$(ipconfig getifaddr $(echo ${line} | cut -d: -f2 2>/dev/null))\n"

        else
            printf "${line}\n"
        fi
    done
}


location(){
    case $1 in
        create)
            [ -z "$2" ] && help && exit 1;
            networksetup -createlocation $2
            ;;
        delete)
            [ -z "$2" ] && help && exit 1;
            networksetup -deletelocation $2
            ;;
        switch)
            [ -z "$2" ] && help && exit 1;
            networksetup -switchtolocation $2
            ;;
        list)
            echo "Locations: "
            networksetup -listlocations
            ;;
        info)
            echo "Current location: $(networksetup -getcurrentlocation)"
            ;;
        *)
            help && exit 1
            ;;
    esac
}



case $1 in
    help)
        help
        ;;
    --list)
        list_netservices
        ;;
    --location)
        shift
        location $@
        ;;
    *)
        help
        ;;
esac
